﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using Tauren.Form.DLL.Base;
using Tauren.Form.DLL.Field_FormDLL;
using Tauren.Form.DLL.Form_TableInfoDLL;
using Tauren.Form.DLL.Resouces;
using Tauren.Form.Entity.Config;
using Tauren.Form.Entity.Const;
using Tauren.Form.Entity.Enum;
using Tauren.Form.Entity.Global;
using Tauren.Form.Entity.Model;
using Tauren.Form.Entity.Output;
using Tauren.Form.Infrastructure.Common;
using Tauren.Form.Infrastructure.Globals;

namespace Tauren.Form.Service.Field_FormBLL
{
    public class FieldService : Base.BaseService, IFieldService
    {
        private IField_FormBusiness business;
        public IForm_TableInfoBusiness _tableInfoBusiness { get; set; }
        private LongCommon longCommon;
        public FieldService(IField_FormBusiness _business, IConnectionBLLBase connectionBLL, IMenuResourcesBusiness resourcesBusiness = null) : base(_business, connectionBLL, resourcesBusiness)
        {
            this.business = _business;
            this.ResourcesInfo = this.GetResources(GlobalConst.RESOURCES_FLAG_MODULE_FIELD_FORM_KEY);
            this.JudePrmission(GlobalConst.RESOURCES_FLAG_MODULE_FIELD_FORM_KEY.ToLower());
            longCommon = new LongCommon();
        }

        #region public
        /// <summary>
        /// 获取表单最新的字段
        /// </summary>
        /// <param name="FormId"></param>
        /// <returns></returns>
        public IResponseMessage FormFields(long FormId, long VersionId)
        {

            List<Field_Form_VersionExt> _Version_Puts = business.GetVersionFields(FormId, VersionId);
            Field_Form_Version_Put put = new Field_Form_Version_Put();
            Field_Form_VersionExt ext = _Version_Puts.FirstOrDefault();
            put.FormId = FormId;
            if (ext != null && ext.VersionId != 0)
            {
                put.AutoId = longCommon.Create();
                put.VersionNo = ext.VersionNo;
                put.UseApplicantEmpId = ext.UseApplicantEmpId;
                put.FormCNName = ext.FormCNName;
                put.FormENName = ext.FormENName;
                if (_Version_Puts.Any())
                {
                    string tablecode = $"'{string.Join("','", _Version_Puts.Select(o => o.TableCode).Distinct())}'";
                    var fromtables = _tableInfoBusiness.GetTableByCode(tablecode);
                    var tables = business.GetTableFields(tablecode);
                    var joinTables = fromtables.Join(tables, a => a.TableCode, b => b.TableCode, (a, b) => { a.TableName = b.TableName; a.TableENName = b.TableENName; return a; }).ToList();
                    var results = _Version_Puts.Join(tables, a => a.TableCode, b => b.TableCode, (a, b) =>
                    {
                        a.AreaUsable = b.TableEnable && !b.TableHaveDelete;
                        return a;
                    }).Distinct().ToList();
                    results.GroupBy(o => new { o.TableCode, o.AreaCNName, o.AreaENName, o.AreaCode, o.AreaUsable, o.MainTable, o.AreaSeq, o.AreaId, o.Presentation, o.Records, o.Rowes, o.Columnes }).ToList().OrderBy(o => o.Key.AreaSeq).ToList().ForEach(g => put.Areas.Add(BuilderArea(g.Key, results, joinTables, tables)));
                }
                else
                {
                    if (ext.UseApplicantEmpId)
                    {
                        Field_Form_Area_Put employee = BuilderEmployeeInfo();
                        if (employee != null)
                            put.Areas.Add(employee);
                    }
                    CreateEmptyArea(put);
                }
            }
            else
            {
                put.FormCNName = ext.FormCNName;
                put.FormENName = ext.FormENName;
                if (ext.UseApplicantEmpId)
                {
                    Field_Form_Area_Put employee = BuilderEmployeeInfo();
                    if (employee != null)
                        put.Areas.Add(employee);
                }
                CreateEmptyArea(put);
            }
            return put.OnSucceed();
        }
        public IResponseMessage TableInfos(QueryModel queryModel)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            TableListModel<Field_Form_Area_Put> tableListModel = new TableListModel<Field_Form_Area_Put>();
            List<TableListHeaderModele> Headers = new List<TableListHeaderModele>();
            Headers.Add(new TableListHeaderModele() { Key = "tableCode", Name = CommonText("autoid"), Width = 70, Type = "primary_key", });
            Headers.Add(new TableListHeaderModele() { Key = "areaCNName", Name = CommonText("thcnname"), Align = "left" });
            Headers.Add(new TableListHeaderModele() { Key = "areaENName", Name = CommonText("thenname"), Align = "left" });
            Headers.Add(new TableListHeaderModele() { Key = "mainTable", Name = CommonText("maintable"), Align = "left" });
            Headers.Add(new TableListHeaderModele() { Key = "mainTableName", Name = CommonText("maintablename"), Align = "left" });
            Headers.Add(new TableListHeaderModele() { Key = "mainTableENName", Name = CommonText("maintableenname"), Align = "left" });
            List<Form_Field_TableInfo_OutPut> tableInfo_OutPuts = business.GetFormFieldTableInfos(long.Parse(queryModel.keyWordFieldValue + ""));
            string tablecode = $"'{string.Join("','", tableInfo_OutPuts.Select(o => o.TableCode))}','{string.Join("','", tableInfo_OutPuts.Select(o => o.ChildTableCode))}'";
            var tables = business.GetTableInfos(tablecode);
            var fromtables = _tableInfoBusiness.GetTableByCode(tablecode);
            var jointable = tables.Join(fromtables, a => a.TableCode, b => b.TableCode, (a, b) => { a.TableEnable = a.TableEnable && b.Enable; a.TableHaveDelete = a.TableHaveDelete && b.HaveDelete; return a; });
            List<Field_Form_Area_Put> _Area_Puts = new List<Field_Form_Area_Put>();
            tableInfo_OutPuts.GroupBy(o => o.TableCode).ToList().ForEach(p =>
            {
                double i = 0.0;
                var mainTable = jointable.FirstOrDefault(o => o.TableCode == p.Key);
                bool mainAreaUsable = mainTable.TableEnable && !mainTable.TableHaveDelete;

                if (mainTable != null)
                {
                    _Area_Puts.Add(new Field_Form_Area_Put()
                    {
                        TableCode = mainTable.TableCode,
                        AreaCNName = mainTable.TableName,
                        AreaENName = mainTable.TableENName,
                        AreaId = longCommon.GenerateRandomCode(6),
                        Columnes = 3,
                        Records = mainTable.Records,
                        Presentation = mainTable.Records ? 1 : 0,
                        Rowes = mainTable.Records ? 10 : 1,
                        Usable = mainAreaUsable,
                        AreaCode = $"from_{mainTable.TableCode}_Info",
                        AreaSeq = mainTable.sequence
                    });
                    p.ToList().Join(tables, a => a.ChildTableCode, b => b.TableCode, (a, b) => new Field_Form_Area_Put
                    {
                        TableCode = a.ChildTableCode,
                        AreaCNName = b.TableName,
                        AreaENName = b.TableENName,
                        AreaId = longCommon.GenerateRandomCode(6),
                        Columnes = 3,
                        Records = b.Records,
                        MainTable = a.TableCode,
                        Presentation = b.Records ? 1 : 0,
                        Rowes = b.Records ? 10 : 1,
                        Usable = b.TableEnable && !b.TableHaveDelete && mainAreaUsable,
                        AreaCode = $"from_{a.ChildTableCode}_Info",
                        MainTableENName = mainTable.TableENName,
                        MainTableName = mainTable.TableName,
                        AreaSeq = b.sequence
                    }).ToList().ForEach(np =>
                   {
                       np.AreaSeq = double.Parse((mainTable.sequence + i).ToString("f2"));
                       i = i + 0.1;
                       _Area_Puts.Add(np);
                   });
                }
            });
            _Area_Puts = _Area_Puts.Where(o => o.Usable).OrderBy(o => o.AreaSeq).ToList();
            tableListModel.Body = _Area_Puts;
            tableListModel.Total = _Area_Puts.Count;
            tableListModel.Header = Headers;
            return tableListModel.Succeed();
        }

        /// <summary>
        /// 保存表单字段
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IResponseMessage Save(Field_Form_Version_InPut model)
        {
            Field_Form_Version _Version = new Field_Form_Version();
            if (model is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            BuliderVersion(model, _Version);
            List<Field_Form_Area> _Areas = new List<Field_Form_Area>();
            List<Field_Form_Area_Fields> _Fields = new List<Field_Form_Area_Fields>();
            List<Field_Form_Area_Fields_Regular> Regulars = new List<Field_Form_Area_Fields_Regular>();
            double i = 0.1;
            model.Areas.ForEach(a =>
            {
                Field_Form_Area area = BuilderArea(a, _Version.AutoId);
                area.Sequence = i;
                _Areas.Add(area);
                double d = 0.1;
                a.Fields.ForEach(f =>
                {
                    Field_Form_Area_Fields field = BuilderField(f, area.AutoId);
                    field.Sequence = d;
                    _Fields.Add(field);
                    f.Regulars.ForEach(r =>
                    {
                        Regulars.Add(new Field_Form_Area_Fields_Regular()
                        {
                            AutoId = longCommon.GenerateRandomCode(8),
                            Regulars = r.Regulars,
                            FieldKey = f.FieldKey,
                            Creator = Global.EmpId,
                            Creatdate = DateTime.Now,
                            Modifier = Global.EmpId,
                            Modifdate = DateTime.Now,
                            FieldId = field.AutoId
                        });
                    });
                    d = d + 0.1;
                }); i = i + 0.1;
            });
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
            {
                ////添加版本
                bool b = business.Add(_Version) >= 0;
                ///添加区域
                if (b)
                    b = business.Add(_Areas) >= 0;
                ///添加字段
                if (b)
                    b = business.Add(_Fields) >= 0;
                ///正则
                if (b)
                    b = business.Add(Regulars) >= 0;
                if (b)
                {
                    ts.Complete();
                    return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
                }
                else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
            }
        }

        /// <summary>
        /// 发布表单字段
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IResponseMessage Publish(Field_Form_Version_InPut model)
        {

            Field_Form_Version _Version = new Field_Form_Version();
            if (model is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            Field_Form form = business.Get<Field_Form>(model.FormId);
            BuliderVersion(model, _Version);
            form.CurrentVersion = _Version.VersionNo;
            form.Modifdate = DateTime.Now;
            form.Modifier = Global.EmpId;
            form.Status = (int)FormStatus.installed;
            List<Field_Form_Area> _Areas = new List<Field_Form_Area>();
            List<Field_Form_Area_Fields> _Fields = new List<Field_Form_Area_Fields>();
            List<Field_Form_Area_Fields_Regular> Regulars = new List<Field_Form_Area_Fields_Regular>();
            double i = 0.1;
            model.Areas.ForEach(a =>
            {
                ///区域
                Field_Form_Area area = BuilderArea(a, _Version.AutoId);
                area.Sequence = i;
                _Areas.Add(area);
                double d = 0.1;
                ///字段
                a.Fields.ForEach(f =>
                {
                    Field_Form_Area_Fields field = BuilderField(f, area.AutoId);
                    field.Sequence = d;
                    _Fields.Add(field);
                    ///正则
                    f.Regulars.ForEach(r =>
                    {
                        Regulars.Add(new Field_Form_Area_Fields_Regular()
                        {
                            AutoId = longCommon.GenerateRandomCode(8),
                            Regulars = r.Regulars,
                            FieldKey = f.FieldKey,
                            Creator = Global.EmpId,
                            Creatdate = DateTime.Now,
                            Modifier = Global.EmpId,
                            Modifdate = DateTime.Now,
                            FieldId = field.AutoId
                        });
                    });
                    d = d + 0.1;
                });
                i = i + 0.1;
            });
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
            {
                ////添加版本
                bool b = business.Add(_Version) >= 0;
                ///添加区域
                if (b)
                    b = business.Add(_Areas) >= 0;
                ///添加字段
                if (b)
                    b = business.Add(_Fields) >= 0;
                ///正则
                if (b)
                    b = business.Add(Regulars) >= 0;
                ///修改表单信息
                if (b) b = business.Update(form);
                if (b)
                {
                    ts.Complete();
                    return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
                }
                else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
            }
        }
        #endregion


        #region private

        /// <summary>
        /// 组装版本信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="_Version"></param>
        private void BuliderVersion(Field_Form_Version_InPut model, Field_Form_Version _Version)
        {
            _Version.AutoId = longCommon.GenerateRandomCode(6);
            _Version.FormId = model.FormId;
            _Version.VersionNo = model.VersionNo + 1;
            _Version.Creatdate = DateTime.Now;
            _Version.Modifdate = DateTime.Now;
            _Version.Creator = Global.EmpId;
            _Version.Modifier = Global.EmpId;
        }


        /// <summary>
        /// 组装区域数据
        /// </summary>
        /// <param name="a"></param>
        /// <param name="versionId"></param>
        /// <returns></returns>

        private Field_Form_Area BuilderArea(Field_Form_Area_Put a, long versionId)
        {
            return new Field_Form_Area()
            {
                AutoId = longCommon.GenerateRandomCode(8),
                AreaCode = a.AreaCode,
                CNName = a.AreaCNName,
                Columnes = a.Columnes,
                VersionId = versionId,
                TableCode = a.TableCode,
                ENName = a.AreaENName,
                Presentation = a.Presentation,
                Records = a.Records,
                Rowes = a.Rowes,
                Sequence = a.AreaSeq,
                Creator = Global.EmpId,
                Creatdate = DateTime.Now,
                Modifier = Global.EmpId,
                Modifdate = DateTime.Now,
                MainTable = a.MainTable
            };
        }

        /// <summary>
        /// 组装区域数据
        /// </summary>
        /// <param name="a"></param>
        /// <param name="versionId"></param>
        /// <returns></returns>

        private Field_Form_Area_Fields BuilderField(Field_Form_Area_Fields_Put f, long areaid)
        {
            return new Field_Form_Area_Fields()
            {
                AutoId = longCommon.GenerateRandomCode(8),
                AreaId = areaid,
                CNName = f.CNName,
                ControlSouces = f.ControlSouces,
                ControlsType = f.ControlsType,
                DefaultValue = f.DefaultValue,
                Editor = f.Editor,
                ENName = f.ENName,
                FieldCode = f.FieldCode,
                FieldKey = f.FieldKey,
                FLength = f.FLength,
                Max = f.Max,
                Min = f.Min,
                Precisions = f.Precisions,
                Required = f.Required,
                SelectType = f.SelectType,
                Show = f.Show,
                Type = f.Type,
                Sequence = f.Sequence,
                Creator = Global.EmpId,
                Creatdate = DateTime.Now,
                Modifier = Global.EmpId,
                Modifdate = DateTime.Now
            };
        }

        /// <summary>
        /// 没有表表达那数据时组装表单信息
        /// </summary>
        /// <param name="tables"></param>
        /// <returns></returns>
        private Field_Form_Area_Put BuilderEmployeeInfo()
        {
            List<TableFields> fields = business.GetTableFields("'employee'");
            var fromtables = _tableInfoBusiness.GetTableByCode("'employee'");
            fields = fields.Join(fromtables, a => a.TableCode, b => b.TableCode, (a, b) =>
            {
                a.TableEnable = a.TableEnable && b.Enable;
                a.TableHaveDelete = a.TableHaveDelete && b.HaveDelete;
                return a;
            }).ToList();
            TableFields table = fields.FirstOrDefault();
            Field_Form_Area_Put put = new Field_Form_Area_Put();
            if (table != null && table.FieldEnable && !table.FieldHaveDelete)
            {
                long areaId = longCommon.GenerateRandomCode(6);
                put = new Field_Form_Area_Put()
                {
                    AreaSeq = 0.1,
                    AreaCNName = "申请人信息",
                    AreaCode = "form_apply_employeebasicinfo",
                    AreaENName = "Applicant Information",
                    TableCode = table.TableCode,
                    Columnes = 3,
                    Usable = table.TableEnable && !table.TableHaveDelete,
                    AreaId = areaId
                };

                put.Fields.Add(new Field_Form_Area_Fields_Put()
                {
                    AreaId = areaId,
                    AutoId = longCommon.GenerateRandomCode(8),
                    ControlsType = ControlType.employee.ToString(),
                    Editor = false,
                    FieldCode = "cnname",
                    FieldKey = $"{put.AreaCode}{GlobalConst.SEPARATOR_DOLLAR}{put.TableCode}{GlobalConst.SEPARATOR_DOLLAR}cnname",
                    Sequence = 0.2,
                    Show = true,
                    Type = ((int)FieldType.varchar).ToString(),
                    Usable = true,
                    SelectType = (int)SelectType.radio,
                    FLength = 200,
                });

                put.Fields.Add(new Field_Form_Area_Fields_Put()
                {
                    AreaId = areaId,
                    AutoId = longCommon.GenerateRandomCode(8),
                    ControlsType = ControlType.text.ToString(),
                    Editor = false,
                    FieldCode = "empcode",
                    FieldKey = $"{put.AreaCode}{GlobalConst.SEPARATOR_DOLLAR}{put.TableCode}{GlobalConst.SEPARATOR_DOLLAR}empcode",
                    Sequence = 0.4,
                    Show = true,
                    Type = ((int)FieldType.varchar).ToString(),
                    Usable = true
                });
                put.Fields.Add(new Field_Form_Area_Fields_Put()
                {
                    AreaId = areaId,
                    AutoId = longCommon.GenerateRandomCode(8),
                    ControlsType = ControlType.text.ToString(),
                    Editor = false,
                    FieldCode = "enname",
                    FieldKey = $"{put.AreaCode}{GlobalConst.SEPARATOR_DOLLAR}{put.TableCode}{GlobalConst.SEPARATOR_DOLLAR}enname",
                    Sequence = 0.5,
                    Show = true,
                    Type = ((int)FieldType.varchar).ToString(),
                    Usable = true,
                    FLength = 200
                });

                put.Fields = put.Fields.Join(fields, a => a.FieldCode.ToLower(), b => b.FieldCode.ToLower(), (a, b) => { a.Usable = b.FieldEnable && !b.FieldHaveDelete; a.CNName = b.FieldName; a.ENName = b.FieldENName; return a; }
                ).ToList();
                put.Fields.Add(new Field_Form_Area_Fields_Put()
                {
                    AreaId = areaId,
                    AutoId = longCommon.GenerateRandomCode(8),
                    ControlsType = ControlType.avatar.ToString(),
                    CNName = "头像",
                    Editor = false,
                    ENName = "Photo",
                    FieldCode = "photo",
                    FieldKey = $"{put.AreaCode}{GlobalConst.SEPARATOR_DOLLAR}{put.TableCode}{GlobalConst.SEPARATOR_DOLLAR}photo",
                    Sequence = 0.1,
                    Show = true,
                    Type = ((int)FieldType.varchar).ToString(),
                    Usable = true,
                    FLength = 200
                });
                put.Fields.Add(new Field_Form_Area_Fields_Put()
                {
                    AreaId = areaId,
                    AutoId = longCommon.GenerateRandomCode(8),
                    ControlsType = ControlType.number.ToString(),
                    CNName = "员工ID",
                    Editor = false,
                    ENName = "Emp Id",
                    FieldCode = "empid",
                    FieldKey = $"{put.AreaCode}{GlobalConst.SEPARATOR_DOLLAR}{put.TableCode}{GlobalConst.SEPARATOR_DOLLAR}empid",
                    Sequence = 0.3,
                    Show = false,
                    Type = ((int)FieldType.bigint).ToString(),
                    Usable = true
                });
            }
            put.Fields = put.Fields.OrderBy(o => o.Sequence).Distinct().ToList();
            return put;

        }
        /// <summary>
        /// 组装字段
        /// </summary>
        private Field_Form_Area_Fields_Put BuilderField(dynamic ext, List<Field_Form_VersionExt> fields, Field_Form_Area_Put area)
        {
            if (ext.FieldId <= 0) return null;
            Field_Form_Area_Fields_Put field = new Field_Form_Area_Fields_Put()
            {
                AreaId = ext.AreaId,
                AutoId = ext.FieldId,
                CNName = ext.CNName,
                ControlSouces = ext.ControlSouces,
                ControlsType = ext.ControlsType,
                DefaultValue = ext.DefaultValue,
                Editor = ext.Editor,
                ENName = ext.ENName,
                FieldCode = ext.FieldCode,
                FieldKey = ext.FieldKey,
                FLength = ext.FLength,
                Max = ext.Max,
                Min = ext.Min,
                Precisions = ext.Precisions,
                Required = ext.Required,
                SelectType = ext.SelectType,
                Sequence = ext.Sequence,
                Show = ext.Show,
                Type = ext.Type,
                Usable = ext.FieldUsable && area.Usable,
            };
            if (area.AreaCode == "form_apply_employeebasicinfo")
            {
                field.Editor = false;
                field.Required = false;
            }
            fields.Where(o => o.FieldId == field.AutoId).ToList().ForEach(o =>
            {
                var condition = BuilderCondition(o);
                if (!(condition is null))
                    field.Conditions.Add(condition);
                var regular = BuilderRegular(o);
                if (!(regular is null))
                    field.Regulars.Add(regular);
            });
            this.ApprovalDefaultValue(field);
            return field;
        }
        /// <summary>
        /// 处理字段默认值
        /// </summary>
        /// <param name="field"></param>
        private void ApprovalDefaultValue(Field_Form_Area_Fields_Put field)
        {
            ///员工
            if (field.ControlsType == ControlType.employee.ToString() && !string.IsNullOrEmpty(field.DefaultValue))
            {
                var empids = field.DefaultValue.Split(new string[] { GlobalConst.SEPARATOR_COMMA }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in empids)
                {
                    field.FieldValue.Add(item);
                }
                List<Entity.Model.Employee> emps = ToUserInfos();
                field.FieldValues = empids.Join(emps, a => a, b => b.EmpId + "", (a, b) =>
                {
                    dynamic res = new { value = a, cnName = b.CNName, enName = b.ENName };
                    return res;
                }).ToList();

            }
            ///组织
            if (field.ControlsType == ControlType.organizational.ToString() && !string.IsNullOrEmpty(field.DefaultValue))
            {
                var orgids = field.DefaultValue.Split(new string[] { GlobalConst.SEPARATOR_COMMA }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in orgids)
                {
                    field.FieldValue.Add(item);
                }
                List<Entity.Model.Organization> orgs = ToOrgInfos();
                field.FieldValues = orgids.Join(orgs, a => a, b => b.OrgId + "", (a, b) =>
                {
                    dynamic res = new { value = a, cnName = b.CNName, enName = b.ENName, orgCode = b.OrgCode };
                    return res;
                }).ToList();

            }
            ///职位
            if (field.ControlsType == ControlType.position.ToString() && !string.IsNullOrEmpty(field.DefaultValue))
            {
                var posids = field.DefaultValue.Split(new string[] { GlobalConst.SEPARATOR_COMMA }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in posids)
                {
                    field.FieldValue.Add(item);
                }
                List<Entity.Model.Position> emps = ToPositionsInfos();
                field.FieldValues = posids.Join(emps, a => a, b => b.PositionId + "", (a, b) =>
                {
                    dynamic res = new { value = a, cnName = b.CNName, enName = b.ENName, positionCode = b.PositionCode };
                    return res;
                }).ToList();
            }
            ///常用参数
            if (field.ControlsType == ControlType.parameter.ToString() && !string.IsNullOrEmpty(field.DefaultValue))
            {
                var paramtersid = field.DefaultValue.Split(new string[] { GlobalConst.SEPARATOR_COMMA }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in paramtersid)
                {
                    field.FieldValue.Add(paramtersid);
                }
                List<Entity.Model.ParameterValue> values = this.business.GetBasicListByQuery<ParameterValue>("maincode", field.ControlSouces + "");
                field.FieldValues = paramtersid.Join(values, a => a, b => b.Code + "", (a, b) =>
                {
                    dynamic res = new { value = a, cnName = b.CNName, enName = b.ENName, parameterCode = b.Code };
                    return res;
                }).ToList();
            }
        }

        /// <summary>
        /// 组装区域
        /// </summary>
        /// <param name="ext"></param>
        /// <returns></returns>
        private Field_Form_Area_Put BuilderArea(dynamic ext, List<Field_Form_VersionExt> fields, List<Form_TableInfoExt> fromtables, List<TableFields> tables)
        {
            Field_Form_Area_Put area = new Field_Form_Area_Put()
            {
                AreaCNName = ext.AreaCNName,
                AreaENName = ext.AreaENName,
                AreaCode = ext.AreaCode,
                AreaSeq = ext.AreaSeq,
                AreaId = ext.AreaId,
                TableCode = ext.TableCode,
                Columnes = ext.Columnes,
                MainTable = ext.MainTable,
                Presentation = ext.Presentation,
                Records = ext.Records,
                Rowes = ext.Rowes,
                Usable = ext.AreaUsable,
            };
            var baseTab = fromtables.FirstOrDefault(o => o.TableCode == ext.MainTable);
            ///主表都被删除和禁用了则子表也要禁用和删除
            if (baseTab != null)
            {
                if (area.Usable)
                {
                    area.Usable = area.Usable && baseTab.Enable && !baseTab.HaveDelete;
                }
                area.MainTableENName = baseTab.TableENName;
                area.MainTableName = baseTab.TableName;
            }
            ///判断子表是否被禁用或则删除
            if (area.Usable)
            {
                var baseTableInfo = fromtables.FirstOrDefault(o => o.TableCode == ext.TableCode);
                if (baseTableInfo != null)
                    area.Usable = area.Usable && baseTableInfo.Enable && !baseTableInfo.HaveDelete;
            }
            var exs = fields.Where(o => o.AreaId == area.AreaId).Join(tables, a => a.FieldCode, b => b.FieldCode, (a, b) => { a.FieldUsable = area.Usable && b.FieldEnable && !b.FieldHaveDelete; return a; }).ToList();
            var exe = fields.Except(exs).Where(o => o.AreaId == area.AreaId);
            if (exe.Any())
            {
                exs.AddRange(exe);
            }
            exs.GroupBy(field => new
            {
                field.AreaId,
                field.FieldId,
                field.CNName,
                field.ENName,
                field.ControlsType,
                field.ControlSouces,
                field.DefaultValue,
                field.Editor,
                field.FieldCode,
                field.FieldKey,
                field.FLength,
                field.Max,
                field.Min,
                field.Precisions,
                field.Required,
                field.SelectType,
                field.Sequence,
                field.Show,
                field.Type,
                field.FieldUsable
            }).ToList().OrderBy(o => o.Key.Sequence).Where(o => o.Key.FieldId > 0).ToList().ForEach(
                fd => area.Fields.Add(BuilderField(fd.Key, fd.ToList(), area)));
            return area;
        }

        /// <summary>
        /// 组装字段规则
        /// </summary>
        /// <param name="fc"></param>
        /// <returns></returns>
        private Field_Form_Area_Fields_Regular BuilderRegular(Field_Form_VersionExt fc)
        {
            if (!string.IsNullOrEmpty(fc.Regulars) && !string.IsNullOrEmpty(fc.Regulars))
                return new Field_Form_Area_Fields_Regular()
                {
                    FieldKey = fc.FieldKey,
                    Regulars = fc.Regulars
                };
            else return null;
        }

        /// <summary>
        /// 组装字段条件
        /// </summary>
        /// <param name="fc"></param>
        /// <returns></returns>
        private Field_Form_Area_Fields_Condition BuilderCondition(Field_Form_VersionExt fc)
        {
            if (!string.IsNullOrEmpty(fc.CascadeField) && !string.IsNullOrEmpty(fc.CascadeFieldValue))
                return new Field_Form_Area_Fields_Condition()
                {
                    Associated = fc.Associated,
                    CascadeField = fc.CascadeField,
                    CascadeFieldValue = fc.CascadeFieldValue,
                    Condition = fc.Condition,
                    FieldKey = fc.FieldKey,
                    LeftBracket = fc.LeftBracket,
                    RightBracket = fc.RightBracket
                };
            else return null;
        }
        private void CreateEmptyArea(Field_Form_Version_Put put)
        {
            List<Form_Field_TableInfo_OutPut> tableInfo_OutPuts = business.GetFormFieldTableInfos(put.FormId);
            string tablecode = $"'{string.Join("','", tableInfo_OutPuts.Select(o => o.TableCode))}','{string.Join("','", tableInfo_OutPuts.Select(o => o.ChildTableCode))}'";
            var tables = business.GetTableInfos(tablecode);
            var fromtables = _tableInfoBusiness.GetTableByCode(tablecode);
            var jointable = tables.Join(fromtables, a => a.TableCode, b => b.TableCode, (a, b) => { a.TableEnable = a.TableEnable && b.Enable; a.TableHaveDelete = a.TableHaveDelete && b.HaveDelete; return a; });
            double i = 0.0;
            tableInfo_OutPuts.GroupBy(o => o.TableCode).ToList().ForEach(p =>
            {
                var mainTable = jointable.FirstOrDefault(o => o.TableCode == p.Key);
                bool mainAreaUsable = mainTable.TableEnable && !mainTable.TableHaveDelete;
                if (mainTable != null)
                {
                    put.Areas.Add(new Field_Form_Area_Put()
                    {
                        TableCode = mainTable.TableCode,
                        AreaCNName = mainTable.TableName,
                        AreaENName = mainTable.TableENName,
                        AreaId = longCommon.GenerateRandomCode(6),
                        Columnes = 3,
                        Records = mainTable.Records,
                        Presentation = mainTable.Records ? 1 : 0,
                        Rowes = mainTable.Records ? 10 : 1,
                        Usable = mainAreaUsable,
                        AreaCode = $"from_{mainTable.TableCode}_Info",
                        AreaSeq = mainTable.sequence
                    });
                    p.ToList().Join(tables, a => a.ChildTableCode, b => b.TableCode, (a, b) => new Field_Form_Area_Put
                    {
                        TableCode = a.ChildTableCode,
                        AreaCNName = b.TableName,
                        AreaENName = b.TableENName,
                        AreaId = longCommon.GenerateRandomCode(6),
                        Columnes = 3,
                        Records = b.Records,
                        MainTable = a.TableCode,
                        Presentation = b.Records ? 1 : 0,
                        Rowes = b.Records ? 10 : 1,
                        Usable = b.TableEnable && !b.TableHaveDelete && mainAreaUsable,
                        MainTableName = mainTable.TableName,
                        MainTableENName = mainTable.TableENName,
                        AreaCode = $"from_{a.ChildTableCode}_Info",
                        AreaSeq = b.sequence
                    }).ToList().ForEach(np =>
                    {
                        np.AreaSeq = double.Parse((mainTable.sequence + i).ToString("f2"));
                        i = i + 0.1;
                        put.Areas.Add(np);
                    });
                }
            });
            put.Areas = put.Areas.OrderBy(o => o.AreaSeq).ToList();
        }
        #endregion
    }
}
